package com.e1xp.deport_management_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.e1xp.deport_management_system.entity.Io;
import com.e1xp.deport_management_system.exception.CustomException;
import com.e1xp.deport_management_system.exception.CustomExceptionType;
import com.e1xp.deport_management_system.mapper.IoMapper;
import com.e1xp.deport_management_system.service.IIoService;
import com.e1xp.deport_management_system.service.IProductService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author E1xP
 * @since 2021-04-09
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class IoServiceImpl extends ServiceImpl<IoMapper, Io> implements IIoService {

    @Resource
    IoMapper ioMapper;

    @Resource
    IProductService productService;

    /**
     * 用于获取最近的count条IO
     *
     * @param instanceId 实例id
     * @param count      限制长度
     * @return List Map IO实体类
     */
    @Override
    public List<Map<String, String>> getRecent(long instanceId, int count) {
        if (count <= 0)
            return null;
        else
            return ioMapper.getRecentIO(instanceId, count);
    }

    /**
     * 获取IO列表
     *
     * @param instanceId 实例id
     * @return List IO列表
     */
    @Override
    public List<Io> getList(long instanceId) {
        QueryWrapper<Io> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("instance_id", instanceId);
        return ioMapper.selectList(queryWrapper);
    }

    /**
     * 用于添加入库记录
     *
     * @param instanceId 实例id
     * @param io         IO实体
     * @throws CustomException 当输入数据不完整时抛出该异常
     */
    @Override
    public void add(long instanceId, Io io) throws CustomException {
        if (io.getProductId() == null ||
                io.getCount() == null || io.getCount() <= 0 ||
                io.getRackId() == null ||
                io.getVendorsId() == null ||
                io.getOperator() == null) {
            //输入数据不完整
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "输入数据不完整");
        }
        io.setInstanceId(instanceId);
        io.setTime(LocalDateTime.now());
        io.setType(0);
        productService.toRack(io.getRackId(), io.getProductId(), io.getCount(), instanceId);
        ioMapper.insert(io);
    }
}
